//
//  TitleBarView.m
//  oschina_song
//
//  Created by song on 16/1/25.
//  Copyright © 2016年 song. All rights reserved.
//

#import "TitleBarView.h"
#import "UIColor+utils.h"

@implementation TitleBarView

-(id)initWithFrame:(CGRect)frame andTitles:(NSArray *)titles
{
    self  = [super initWithFrame:frame];
    if(self){
        _titleButtons = [NSMutableArray array];
        CGFloat btnWidth = frame.size.width / titles.count;
        CGFloat btnHeight = frame.size.height;
        
        [titles enumerateObjectsUsingBlock:^(id  _Nonnull title, NSUInteger idx, BOOL * _Nonnull stop) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            [btn setTitle:title forState:UIControlStateNormal];
            btn.titleLabel.font = [UIFont systemFontOfSize:15];
            btn.tag = idx;
            [btn setTitleColor:[UIColor colorWithHex:0x909090] forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
            btn.frame  =CGRectMake(btnWidth * idx, 0, btnWidth, btnHeight);
            [_titleButtons addObject:btn];
            [self addSubview:btn];
            
        }];
        
        
        UIButton *firstbtn =_titleButtons[0];
        [firstbtn setTitleColor:[UIColor colorWithHex:0x009000] forState:UIControlStateNormal];
    }
    
    return self;
 
}

-(void)onClick:(UIButton *)btn
{
    if(_currentIndex != btn.tag)
    {
        UIButton *prebtn = _titleButtons[_currentIndex];
        [prebtn setTitleColor:[UIColor colorWithHex:0x909090] forState:UIControlStateNormal];
        
        
        [btn setTitleColor:[UIColor colorWithHex:0x009000] forState:UIControlStateNormal];
        _currentIndex = btn.tag;
        if(_titleButtonCLicked){_titleButtonCLicked(_currentIndex);};
    }
}


@end
